package eu.news.servlet.query;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.news.data.hibernate.dao.HB_NewsDAO;
import eu.news.data.hibernate.pojo.HB_News;
import eu.news.template.NewsStatic;

/**
 * Servlet implementation class ViewNews
 */
public class ViewNews extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ViewNews() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri=request.getRequestURI();
		String[] fields=uri.split("/");
		String _id=fields[fields.length-1];
		if(_id.endsWith(".html"))
			_id=_id.substring(0,_id.indexOf('.'));
		int nid=Integer.parseInt(_id);
		response.setCharacterEncoding("UTF-8");
		if(!NewsStatic.exists(nid)){
			HB_NewsDAO nDao=new HB_NewsDAO();
			HB_News news=nDao.getById(nid);
			if(news==null||news.getState()!=News.State.STATE_PUBLISHED){
				response.sendError(404);
				return;
			}
			response.getWriter().print(NewsStatic.updateData(news, request));
		}else
			response.getWriter().print(NewsStatic.readData(nid));
	}

}
